package cn.edu.neusoft.yuejian4.yuejian_4.activity;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;

import cn.edu.neusoft.yuejian4.yuejian_4.Config.Server;
import cn.edu.neusoft.yuejian4.yuejian_4.R;
import cn.edu.neusoft.yuejian4.yuejian_4.javaBean.Success;
import cn.edu.neusoft.yuejian4.yuejian_4.javaBean.User;
import cn.edu.neusoft.yuejian4.yuejian_4.listener.TListener;
import cn.edu.neusoft.yuejian4.yuejian_4.model.MyModel;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static cn.edu.neusoft.yuejian4.yuejian_4.Config.HeadPic.headPicpath;
import static cn.edu.neusoft.yuejian4.yuejian_4.Config.ImageUtils.cropImageUri;
import static cn.edu.neusoft.yuejian4.yuejian_4.Config.ImageUtils.handlerImageOnKitKat;
import static cn.edu.neusoft.yuejian4.yuejian_4.Config.ImageUtils.saveBitmapFile;

/**
 * Created by Lix on 2018/10/login_bg2.
 */

public class MySetHeadpicActivity extends AppCompatActivity implements View.OnClickListener{

    //调用系统相机拍摄、剪切的返回码
    private static final int REQUEST_CODE_FOR_PIC = 1;
    private static final int PHOTO_REQUEST_CUT = 2;// 结果
    private static final int CROP_PICTURE = 3;

    private ImageView back,myNewPic;
    private Button saveSet,changePic;
    private TextView test1;
    private SharedPreferences sp;
    private int uid;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_setimg);
        sp = getSharedPreferences("userinfo", MODE_PRIVATE);
        uid = sp.getInt("uid", 4);
        MyModel myModel = new MyModel();
        myModel.userinfo(uid,userinfo);
        initView();
        initEvent();
    }
    TListener<User> userinfo = new TListener<User>() {
        @Override
        public void onResponse(User user) {
            Picasso.with(getApplicationContext())
                    .load(Server.PIC_URL_J+user.getPic())
                    .placeholder(R.drawable.ic_default_img)
                    .memoryPolicy(MemoryPolicy.NO_CACHE)
                    .into(myNewPic);
        }

        @Override
        public void onFail(String msg) {

        }
    };
    private void initView(){
        back = (ImageView)findViewById(R.id.my_set_img_back);
        myNewPic = (ImageView)findViewById(R.id.set_my_img);
        saveSet =(Button)findViewById(R.id.btn_set_saveimg);
        changePic = (Button)findViewById(R.id.btn_updade_img);
        test1 = (TextView)findViewById(R.id.test1);

    }
    private void initEvent(){
        back.setOnClickListener(this);
        changePic.setOnClickListener(this);
        saveSet.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_set_img_back:
                finish();
                break;
            case R.id.btn_updade_img:
                //动态获取相机权限
                if (ContextCompat.checkSelfPermission(MySetHeadpicActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
                        PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MySetHeadpicActivity.this, new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    getHeadPic();
                }
                break;
            case R.id.btn_set_saveimg:

                MultipartBody.Part head_pic = null;
                File file = null;

                file = new File(headPicpath);

                MediaType mediaType = MediaType.parse("multipart/form-data");
                RequestBody uid = RequestBody.create(mediaType,Integer.toString(4));
                RequestBody requestBody = RequestBody.create(mediaType, file);
                head_pic = MultipartBody.Part.createFormData("head_pic", file.getName(), requestBody);

                test1.setText(file.getName());

                MyModel myModel = new MyModel();
                myModel.updateMyHeadpic(uid,head_pic, new TListener<Success>() {

                    @Override
                    public void onResponse(Success success) {
                        if(success.getError().equals("0")){
                            Toast.makeText(MySetHeadpicActivity.this,"修改头像成功", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(MySetHeadpicActivity.this,"错误信息"+success.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                    @Override
                    public void onFail(String msg) {

                    }
                });
                break;
        }
    }

    private void getHeadPic() {
        //设置intent，指定打开系统相机
        Intent intent = new Intent();
        intent.setAction("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        //启动相机或图库，requestcode传入预定义好的重拍返回码 REQUEST_CODE_FOR_PIC
        startActivityForResult(intent, REQUEST_CODE_FOR_PIC);
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_FOR_PIC) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                handlerImageOnKitKat(this, data);
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            if (data != null) {
                Bitmap bitmap = data.getParcelableExtra("data");
                myNewPic.setImageBitmap(bitmap);
            }
        } else if (requestCode == CROP_PICTURE) {
            // 取得裁剪后的图片
            if (resultCode == RESULT_OK) {
                try {
                    if (cropImageUri != null) {
                        Bitmap headShot = BitmapFactory.decodeStream(getContentResolver().openInputStream(cropImageUri));
                        saveBitmapFile(headShot);
                        myNewPic.setImageBitmap(headShot);

                    } else {
                        Toast.makeText(MySetHeadpicActivity.this,"获取图片路径失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
